﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace Douban.Api.Authorization
{
    public abstract class ConsumerBase
    {
        protected ConsumerBase(IAccessTokenManager manager)
        {
            TokenManager = manager;
        }

        public IAccessTokenManager TokenManager { get; private set; }

        public string ConsumerKey { get; set; }

        public string ConsumerSecret { get; set; }

        public Uri ProcessUserAuthorization(ServiceProviderDescriptor descriptor, out string token, out string tokenSecret)
        {
            QueryParameterCollection collection = QueryParameterCollection.Resolve(
                GetAuthorizationResult(null, null, descriptor.RequestTokenEndpoint.Location));

            token = collection.Get(OAuthKeys.OAuthTokenKey);
            tokenSecret = collection.Get(OAuthKeys.OAuthTokenSecretKey);

            return new Uri(descriptor.AuthorizeEndpoint.Location.AbsoluteUri + "?oauth_token=" + token);
        }

        public AuthorizedTokenResponse ProcessUserAuthorization(
            AuthorizedTokenRequest request, ServiceProviderDescriptor descriptor)
        {
            AuthorizedTokenResponse response = new AuthorizedTokenResponse();

            QueryParameterCollection collection = QueryParameterCollection.Resolve(
                GetAuthorizationResult(request.Token, request.TokenSecret, descriptor.AccessTokenEndpoint.Location));

            response.Token = collection.Get(OAuthKeys.OAuthTokenKey);
            response.TokenSecret = collection.Get(OAuthKeys.OAuthTokenSecretKey);

            TokenManager.StoreToken(response.Token, response.TokenSecret);

            return response;
        }

        protected virtual string GetAuthorizationResult(string token, string tokenSecret, Uri uri)
        {
            Uri requestTokenUri = OAuthWebRequestUtility.GenerateUri(token, tokenSecret, uri, this);

            WebClient client = new WebClient();
            return client.DownloadString(requestTokenUri);
        }
    }
}
